#include "DXUT.h"
#include "XMesh.h"


XMesh::XMesh(void)
{
}

XMesh::~XMesh(void)
{
}

HRESULT XMesh::LoadXFile(IDirect3DDevice9* pd3dDevice, TCHAR* strFilePath)
{
	HRESULT hr;
	ID3DXBuffer* adjBuffer(NULL);
	ID3DXBuffer* mtrlBuffer(NULL);

	if (FAILED(hr = D3DXLoadMeshFromX(strFilePath, D3DXMESH_MANAGED, pd3dDevice, &adjBuffer, &mtrlBuffer, 0, &m_dwNumMtrls, &m_pMesh)))
		return DXTRACE_ERR( TEXT("LoadCar"), hr );

	if (mtrlBuffer && m_dwNumMtrls)
	{
		D3DXMATERIAL* mtrls(reinterpret_cast<D3DXMATERIAL*>(mtrlBuffer->GetBufferPointer()));

		m_arrMtrl.reserve(m_dwNumMtrls);
		m_arrTex.reserve(m_dwNumMtrls);
		for (DWORD i = 0; i < m_dwNumMtrls; ++i)
		{
			m_arrMtrl.push_back(mtrls[i].MatD3D);

			if (mtrls[i].pTextureFilename)
			{
				IDirect3DTexture9* tex(0);

				TCHAR lpStr[256];
				int strBufSize(256);
				MultiByteToWideChar(CP_ACP, 0, mtrls[i].pTextureFilename, -1, lpStr, strBufSize);

				D3DXCreateTextureFromFile(pd3dDevice, lpStr, &tex);

				m_arrTex.push_back(tex);
			}
			else
			{
				m_arrTex.push_back(0);
			}
		}

		mtrlBuffer->Release();
	}

	adjBuffer->Release();

	return S_OK;
}

void XMesh::Release()
{
	m_pMesh->Release();

	m_arrMtrl.clear();

	for (TextureContainer::iterator texIter = m_arrTex.begin();
		texIter != m_arrTex.end();
		++texIter)
	{
		(*texIter)->Release();
	}
	m_arrTex.clear();
}